<?php
/** @noinspection PhpUnused */

namespace app\admin\controller\shop\order;

use app\admin\controller\shop\Base;
use app\shop\enums\order\OrderExportStatus;
use app\shop\library\ShopHelper;
use app\shop\service\OrderExportService;
use think\db\exception\DbException;
use Throwable;

/**
 * 订单导出日志管理
 */
class Export extends Base
{
    /**
     * Export模型对象
     * @var object
     * @phpstan-var \app\admin\model\shop\order\Export
     */
    protected object $model;

    protected array|string $preExcludeFields = ['id', 'create_time'];

    protected string|array $quickSearchField = ['admin.nickname'];

    protected array $noNeedPermission = ['getTableHeadField', 'retryTask'];

    protected bool $modelSceneValidate = true;

    protected array $withJoinTable = ['admin' => ['id', 'nickname']];

    private OrderExportService $orderExportService;

    public function initialize(): void
    {
        parent::initialize();
        $this->model = new \app\admin\model\shop\order\Export;

        $this->orderExportService = new OrderExportService();
    }

    /**
     * 若需重写查看、编辑、删除等方法，请复制 @see \app\admin\library\traits\Backend 中对应的方法至此进行重写
     */

    /**
     * 列表
     * @return void
     * @throws Throwable
     * @throws DbException
     */
    public function index(): void
    {
        if ($this->request->param('select')) {
            $this->select();
        }
        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->field($this->indexField)
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($where)
            ->order($order)
            ->append(['time_range'])
            ->paginate($limit)
            ->each(function ($item) {
                $item['export_fields'] = implode(
                    ',',
                    array_column(ShopHelper::json_to_array($item['export_fields']), 'name')
                );
                $item['file_exist']    = !empty($item['export_file_path']) &&
                    file_exists(public_path() . $item['export_file_path']);
            });

        $this->success('', [
            'list'   => $res->items(),
            'total'  => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }

    /**
     * 导出任务重试
     * @return void
     */
    public function retryTask(): void
    {
        $data = $this->request->post();

        $id = $data['id'] ?? 0;

        if (!$id) {
            $this->error('缺少导出任务ID');
        }

        $record = $this->model->where('id', $id)->findOrEmpty();

        if ($record->isEmpty()) {
            $this->error('导出任务已被删除,请刷新页面');
        }

        if ($record->status == OrderExportStatus::RUNNING) {
            $this->error('导出任务正在运行中,请稍后再试');
        }

        try {
            $record->status = OrderExportStatus::WAITING;
            $record->save();

            $this->orderExportService->addExportOrderJob($record->id);
        } catch (Throwable $e) {
            $this->error('任务重新运行失败', ['err' => $e->getMessage()]);
        }

        $this->success('任务重新运行成功');
    }

    /**
     * 获取表头字段
     * @return void
     */
    public function getTableHeadField(): void
    {
        $this->success('', $this->orderExportService->orderExportField());
    }
}